package com.xwaiy.xwaiyrpc.protocol;

import com.xwaiy.xwaiyrpc.exception.RpcException;
import com.xwaiy.xwaiyrpc.exception.enums.ErrorCode;
import com.xwaiy.xwaiyrpc.serializer.Serializer;
import com.xwaiy.xwaiyrpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * 编码器
 * @Author Xwaiy
 * @Date 2025/8/29 11:45
 **/
public class Encoder {

    public static Buffer encode(ProtocolMessage<?> msg) throws IOException {
        if(msg == null || msg.getHeader() == null) {
            return Buffer.buffer();
        }

        ProtocolMessage.Header header = msg.getHeader();

        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        SerializerEnum serializerEnum = SerializerEnum.getEnumByKey(header.getSerializer());
        if(serializerEnum == null) {
            throw new RpcException(ErrorCode.PROTOCOL_INVALID_MESSAGE, "序列化协议不存在");
        }

        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bytes = serializer.serialize(msg.getBody());
        buffer.appendInt(bytes.length);
        buffer.appendBytes(bytes);
        return buffer;
    }
}
